package sm.upgrade;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.codec.type.Logical;
import sm.upgrade.api.UpgradePhase;
import sm.util.SMMap;

public class CMKMUpgrade implements UpgradePhase {
	private static Logger logger = LoggerFactory.getLogger(UpgradePhase.class);

	private HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	private String getStatus(String phase) {
		if ("KM 1 Triage".equals(phase))
			return "triage";

		else if ("KM 2 Revise".equals(phase))
			return "revise";

		else if ("KM 3 Review Read-only".equals(phase))
			return "review";

		else if ("KM 4 Conclude".equals(phase))
			return "conclude";
		else
			return "triage";
	}

	@Override
	public void upgrade() {
		logger.info("Upgrading KM for Change Management...");

		List<Object> cm3rs = template.find(
				"from cm3r where category = ? and open = ?", new Object[] {
						"KM Document", Logical.TRUE });

		for (Object cm3r : cm3rs) {
			SMMap cm3rMap = (SMMap) cm3r;
			String id = (String) cm3rMap.get("id");
			SMMap kmdocument = (SMMap) template.get("kmdocument", id);
			if (kmdocument != null) {
				kmdocument.put("status",
						getStatus((String) cm3rMap.get("current_phase")));
				kmdocument.put("assignedEditor", cm3rMap.get("assigned_to"));
				kmdocument.put("documentOwner", cm3rMap.get("coordinator"));
				template.update("kmdocument", kmdocument);
			}

			// Change record related to the kmdocument ID to be forced to
			// 'closed' status
			cm3rMap.put("open", Logical.FALSE);
			cm3rMap.put("completion_code", 1d);
			cm3rMap.put("status", "closed");
			template.update("cm3r", cm3rMap);
		}

		logger.info("  Finished upgrading KM for Change Management.");

	}

}
